package com.aoxun.android.gridmanager.common;

import com.aoxun.android.gridmanager.BuildConfig;
import com.aoxun.android.gridmanager.Constant;
import com.google.gson.Gson;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.CallAdapter;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
//import retrofit2.converter.simplexml.SimpleXmlConverterFactory;

/**
 * Created by huanglong on 2017/6/27.
 */

public class RetrofitFactory {

    private static OkHttpClient getOkHttpClient(){
        OkHttpClient.Builder okbuilder = new OkHttpClient.Builder();

        if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            okbuilder.addInterceptor(logging);
        }

        //if(isXml)
        //    okbuilder.addInterceptor(new XmlInterceptor());

        okbuilder.connectTimeout(18 * 1000, TimeUnit.MILLISECONDS)
                .readTimeout(18 * 1000, TimeUnit.MILLISECONDS);
        return okbuilder.build();
    }

    private static Retrofit createRetrofit(String baseUrl, CallAdapter.Factory adapterFactory, Converter.Factory converterFactory){
        Retrofit.Builder builder = new Retrofit.Builder();
        builder.client(getOkHttpClient())
                .baseUrl(baseUrl)
                .addCallAdapterFactory(adapterFactory)
                .addConverterFactory(converterFactory);
        return builder.build();
    }


    public static Retrofit getJsonRetrofit(){
        return createRetrofit(Constant.BASE_URL,
                RxJava2CallAdapterFactory.create(),
                GsonConverterFactory.create(GsonUtil.getInstance().getGson()));
    }
/*
    public static Retrofit getXmlRetrofit(){
        return createRetrofit("http://pay.jinqiandun.com/",
                RxJava2CallAdapterFactory.create(),
                SimpleXmlConverterFactory.create(),true);
    }

    public static <T> T createXmlService(Class<T> cls){
        return getXmlRetrofit().create(cls);
    }
*/
    public static <T> T createJsonService(Class<T> cls){
        return getJsonRetrofit().create(cls);
    }
}
